package com.hfb.io.netty.chat;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.GlobalEventExecutor;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ChatServerHandler extends SimpleChannelInboundHandler<String> {
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端连接通道建立完成");
        Channel channel = ctx.channel();
        String msg = String.format("[%s]:客户端[%s]上线了!\n",
            sdf.format(new Date()),
            channel.remoteAddress());
        channelGroup.writeAndFlush(msg);

        channelGroup.add(channel);
        System.out.printf(msg);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        Channel channel = ctx.channel();
        String sf = "[%s]发送了消息：%s\n";
        channelGroup.forEach(ch->{
            String m;
            if (channel != ch) {    // 不是当前的channel，转发消息
                m = "客户端:" + channel.remoteAddress();
            } else {    // 回显自己发送的消息给自己
                m = "自己";
            }
            ch.writeAndFlush(String.format(sf, m, msg));
        });

        ByteBuf buf = (ByteBuf) msg;

        String recieved = getMessage(buf);
        System.err.println("服务器接收到客户端消息：" + recieved);

        String message = "你好，客户端";
        ctx.writeAndFlush(getSendByteBuf(message));
        System.err.println("服务器回复消息："+message);
    }

    @Override
    protected void messageReceived(ChannelHandlerContext channelHandlerContext, String s) {
        System.err.println("服务器接收到客户端消息：" + s.trim());
    }

    /**
     * 数据读取完毕的处理方法
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//        ByteBuf buf = Unpooled.compositeBuffer();
//        ctx.writeAndFlush(buf);
        Channel channel = ctx.channel();
        String msg = String.format("[%s]:客户端[%s]下线了!\n",
            sdf.format(new Date()),
            channel.remoteAddress());
        channelGroup.writeAndFlush(msg);
        System.out.println(msg);
        System.out.printf("channelGroup.size:%s", channelGroup.size());

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.channel().close();
    }

    /*
     * 从ByteBuf中获取信息 使用UTF-8编码返回
     */
    private String getMessage(ByteBuf buf) {

        byte[] con = new byte[buf.readableBytes()];
        buf.readBytes(con);
        return new String(con, CharsetUtil.UTF_8);
    }

    private ByteBuf getSendByteBuf(String message) {

        byte[] req = message.getBytes(CharsetUtil.UTF_8);
        ByteBuf pingMessage = Unpooled.buffer();
        pingMessage.writeBytes(req);

        return pingMessage;
    }
}
